package com.base.controller.system.user;

import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.base.controller.base.BaseController;
import com.base.entity.Page;
import com.base.entity.system.Menu;
import com.base.entity.system.Role;
import com.base.entity.system.User;
import com.base.service.system.menu.MenuService;
import com.base.service.system.role.RoleService;
import com.base.service.system.user.UserService;
import com.base.util.AppUtil;
import com.base.util.Const;
import com.base.util.FileDownload;
import com.base.util.FileUpload;
import com.base.util.GetPinyin;
import com.base.util.Jurisdiction;
import com.base.util.ObjectExcelRead;
import com.base.util.ObjectExcelView;
import com.base.util.PageData;
import com.base.util.PathUtil;
import com.base.util.RightsHelper;
import com.base.util.Tools;

/**
 * @Description: [用户控制器]
 * @Author: [lichunan]
 * @CreateDate: [2017/12/20 9:35]
 * @Version: [v1.0]
 * @UpdateDate: [2017/12/20 9:35]
 * @UpdateRemark: [用户控制器] @PreviousVersion：[]
 */
@Controller
@RequestMapping(value = "/userControl")
public class UserController extends BaseController {

	private static final long serialVersionUID = 1L;

	@Autowired
	private UserService userService;
	
	@Autowired
	private MenuService menuService;
	
	@Autowired
	private RoleService roleService;

	@RequestMapping(value = "/goUserLogin")
	public ModelAndView goUserLogin() throws Exception {

		ModelAndView modelAndView = this.getModelAndView();
		PageData pageData = this.getPageData();

		pageData.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME));
		modelAndView.setViewName("system/admin/login");
		modelAndView.addObject("pd", pageData);

		return modelAndView;

	}

	@RequestMapping(value = "/test", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String test(@RequestBody User newUser) {

		System.out.println(newUser.getPassword());

		return newUser.getPassword();

	}

	/**
	 * 登录验证
	 * 
	 * @param user
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/newLogin", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String userLogin(@RequestBody User user) throws Exception {

		String code = user.getCode();
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		String sessionCode = (String) session.getAttribute(Const.SESSION_SECURITY_CODE);
		// 校验验证码
		if (!sessionCode.equalsIgnoreCase(code)) {
			return getLoginResponseJSON("400", "invalid verification code");
		}

		PageData pageData = this.getPageData();
		HttpServletRequest request = this.getRequest();

		String passwd = new SimpleHash("SHA-1", user.getUserName(), user.getPassword()).toString();

		pageData.put("userName", user.getUserName());
		pageData.put("password", passwd);
		pageData.put("IP", getClientIP(request));
		pageData.put("lastLogin", getCurrentTime());

		// 校验用户名和密码
		if (!userService.validateUser(pageData)) {
			return getLoginResponseJSON("400", "invalid username ");
		}

		// 获取用户信息
		HashMap<?, ?> queryResult = userService.getUserByUserName(pageData);
		if (queryResult == null) {
			return getLoginResponseJSON("500", "internal server error");
		}
		Integer userID = (Integer) queryResult.get("USER_ID");
		String roleId = (String) queryResult.get("ROLE_ID");
		user.setUserID(userID);
		user.setName((String) queryResult.get("NAME"));
		user.setRights((String) queryResult.get("RIGHTS"));
		user.setRoleID(roleId);
		user.setStatus((String) queryResult.get("STATUS"));
		user.setBz((String) queryResult.get("BZ"));
		user.setBz((String) queryResult.get("SKIN"));
		user.setBz((String) queryResult.get("EMAIL"));
		user.setBz((String) queryResult.get("NUMBER"));
		user.setBz((String) queryResult.get("PHONE"));
		user.setBz(String.valueOf(queryResult.get("MAN_BUYER_ID")));
		user.setLastLogin(getCurrentTime());
		user.setIP(getClientIP(this.getRequest()));

		// 校验用户状态
		if (!userService.isUserStatusActive(pageData)) {
			return getLoginResponseJSON("400", "invalid user status");
		}

		// 更新用户信息
		if (!userService.updateLoginInfo(pageData)) {
			return getLoginResponseJSON("500", "system is busy");
		}

		// shiro验证
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
		try {
			subject.login(token);
		} catch (AuthenticationException e) {
			return getLoginResponseJSON("500", "internal server error");
		}

		// 记录用户登录流水记录
		PageData flowRecorData = new PageData();
		flowRecorData.put("usiID", userID);
		flowRecorData.put("token", "1");
		flowRecorData.put("terminalType", "2");
		flowRecorData.put("operatingType", "1");
		flowRecorData.put("createdBy", "admin");
		flowRecorData.put("creationDate", getCurrentTime());
		flowRecorData.put("lastUpdateBy", "admin");
		flowRecorData.put("lastUpdateDate", getCurrentTime());
		flowRecorData.put("callCnt", 1);
		flowRecorData.put("remark", "default");
		flowRecorData.put("stsCD", "a");

		if (!userService.insertNewLoginRecord(flowRecorData)) {
			return getLoginResponseJSON("500", "system is busy");
		}

		Role newRole = roleService.findRoleById(Integer.parseInt(user.getRoleID()));
		user.setRole(newRole);
		session.setAttribute(Const.SESSION_USER, user);
		session.setAttribute(Const.TOKEN, token);
		session.setAttribute(Const.SESSION_USERNAME, user.getUserName());
		session.setAttribute(Const.ROLE_ID, roleId);

		return getLoginResponseJSON("200", "userControl/mainIndex");
	}

	/**
	 * 访问登录页
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login_toLogin")
	public ModelAndView toLogin() throws Exception {
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); // 读取系统名称
		mv.setViewName("system/admin/login");
		mv.addObject("pd", pd);
		return mv;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/mainIndex")
	public ModelAndView toMainIndex() throws Exception {
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); // 读取系统名称
		try {
			Subject currentUser = SecurityUtils.getSubject();
			Session session = currentUser.getSession();
			User user = (User) session.getAttribute(Const.SESSION_USER);
			if (user != null) {
				session.setAttribute(Const.SESSION_USERNAME, user.getUserName()); // 放入用户名
				Role newRole = user.getRole();
				String visibleMenuId = newRole.getVisibleMenuId();
				List<Menu> allmenuList = new ArrayList<Menu>();
				if (null == session.getAttribute(Const.SESSION_allmenuList)) {
					allmenuList = menuService.listAllMenu();
					for (Menu menu : allmenuList) {
						menu.setHasMenu(RightsHelper.newTestRights(visibleMenuId, String.valueOf(menu.getMenuId())));
						if (menu.isHasMenu()) {
							List<Menu> subMenuList = menu.getSubMenu();
							for (Menu sub : subMenuList) {
								sub.setHasMenu(true);// 默认将子菜单都勾选（如要改动需配合权限管理页面修改)
							}
						}
					}
					session.setAttribute(Const.SESSION_allmenuList, allmenuList); // 菜单权限放入session中
				} else {
					allmenuList = (List<Menu>) session.getAttribute(Const.SESSION_allmenuList);
				}

				// 切换菜单
				List<Menu> menuList = new ArrayList<Menu>();
				if (null == session.getAttribute(Const.SESSION_menuList)) {
					List<Menu> menuList1 = new ArrayList<Menu>();
					List<Menu> menuList2 = new ArrayList<Menu>();

					// 拆分菜单
					for (int i = 0; i < allmenuList.size(); i++) {
						Menu menu = allmenuList.get(i);
						if ("1".equals(menu.getMenuType())) {
							menuList1.add(menu);
						} else {
							menuList2.add(menu);
						}
					}

					session.removeAttribute(Const.SESSION_menuList);
					if ("2".equals(session.getAttribute("changeMenu"))) {
						session.setAttribute(Const.SESSION_menuList, menuList1);
						session.removeAttribute("changeMenu");
						session.setAttribute("changeMenu", "1");
						menuList = menuList1;
					} else {
						session.setAttribute(Const.SESSION_menuList, menuList2);
						session.removeAttribute("changeMenu");
						session.setAttribute("changeMenu", "2");
						menuList = menuList2;
					}
				} else {
					menuList = (List<Menu>) session.getAttribute(Const.SESSION_menuList);
				}

				mv.setViewName("system/admin/index");
				mv.addObject("user", user);
				mv.addObject("menuList", menuList);
			} else {
				mv.setViewName("system/admin/login");// session失效后跳转登录页面
			}

		} catch (Exception e) {
			mv.setViewName("system/admin/login");
			logger.error(e.getMessage(), e);
		}

		mv.setViewName("system/admin/index");
		mv.addObject("pd", pd);
		return mv;
	}

	public Map<String, String> getUQX(Session session) {
		PageData pd = new PageData();
		Map<String, String> map = new HashMap<String, String>();
		try {
			String USERNAME = session.getAttribute(Const.SESSION_USERNAME).toString();
			pd.put(Const.SESSION_USERNAME, USERNAME);
			String ROLE_ID = userService.findByUId(pd).get("ROLE_ID").toString();

			pd.put("ROLE_ID", ROLE_ID);

			PageData pd2 = new PageData();
			pd2.put(Const.SESSION_USERNAME, USERNAME);
			pd2.put("ROLE_ID", ROLE_ID);

			pd = roleService.findObjectById(pd);

			pd2 = roleService.findGLbyrid(pd2);
			if (null != pd2) {
				map.put("FX_QX", pd2.get("FX_QX").toString());
				map.put("FW_QX", pd2.get("FW_QX").toString());
				map.put("QX1", pd2.get("QX1").toString());
				map.put("QX2", pd2.get("QX2").toString());
				map.put("QX3", pd2.get("QX3").toString());
				map.put("QX4", pd2.get("QX4").toString());

				pd2.put("ROLE_ID", ROLE_ID);
				pd2 = roleService.findYHbyrid(pd2);
				map.put("C1", pd2.get("C1").toString());
				map.put("C2", pd2.get("C2").toString());
				map.put("C3", pd2.get("C3").toString());
				map.put("C4", pd2.get("C4").toString());
				map.put("Q1", pd2.get("Q1").toString());
				map.put("Q2", pd2.get("Q2").toString());
				map.put("Q3", pd2.get("Q3").toString());
				map.put("Q4", pd2.get("Q4").toString());
			}

			map.put("adds", pd.getString("ADD_QX"));
			map.put("dels", pd.getString("DEL_QX"));
			map.put("edits", pd.getString("EDIT_QX"));
			map.put("chas", pd.getString("CHA_QX"));

			this.getRemortIP(USERNAME);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return map;
	}

	public void getRemortIP(String USERNAME) throws Exception {
		PageData pd = new PageData();
		HttpServletRequest request = this.getRequest();
		String ip = "";
		if (request.getHeader("x-forwarded-for") == null) {
			ip = request.getRemoteAddr();
		} else {
			ip = request.getHeader("x-forwarded-for");
		}
		pd.put("USERNAME", USERNAME);
		pd.put("IP", ip);
		userService.saveIP(pd);
	}

	/**
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goUserRegister")
	public ModelAndView goUserRegister() throws Exception {

		ModelAndView modelAndView = this.getModelAndView();
		PageData pageData = this.getPageData();

		pageData.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME));
		modelAndView.setViewName("system/admin/newRegister");
		modelAndView.addObject("pd", pageData);

		return modelAndView;

	}

	/**
	 * 用户注册
	 * @param user
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/userRegister", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String userRegister(@RequestBody User user) throws Exception {

		String userName = user.getUserName();
		String password = new SimpleHash("SHA-1", user.getUserName(), user.getPassword()).toString();
		String name = user.getName();
		String skin = user.getSkin();
		String email = user.getEmail();
		String phone = user.getPhone();
		String roleID = user.getRoleID();

		PageData pageData = this.getPageData();

		pageData.put("userName", userName);
		pageData.put("password", password);
		pageData.put("name", name);
		pageData.put("skin", skin);
		pageData.put("email", email);
		pageData.put("phone", phone);
		pageData.put("roleID", roleID);
		pageData.put("IP", getClientIP(this.getRequest()));
		pageData.put("lastLogin", getCurrentTime());
		pageData.put("rights", "1");
		pageData.put("status", "a");
		pageData.put("number", "1111");

		RegisterResponseMessage message = new RegisterResponseMessage();
		String code = "200";

		if (userService.isUserExists(pageData) != 0) {
			code = "400";
			message.setUserName("invalid user name");
		}

		if (userService.isEmailExists(pageData) != 0) {
			code = "400";
			message.setEmail("invalid email address");
		}
		if (userService.isPhoneExists(pageData) != 0) {
			code = "400";
			message.setPhone("invalid phone number");
		}

		if (code != "200") {
			return getLoginResponseJSONWithResponse("400", message);
		}

		if (!userService.insertNewUser(pageData)) {
			code = "400";
			message.setName("invalid user name");
		}

		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
		try {
			subject.login(token);
		} catch (AuthenticationException e) {
			code = "400";
			message.setName("invalid user name");
		}

		HashMap<String, Object> queryResult = userService.getUserByUserName(pageData);
		if (queryResult == null) {
			code = "400";
			message.setName("invalid user name");
		}
		PageData flowRecorData = new PageData();

		flowRecorData.put("usiID", queryResult.get("USER_ID"));
		flowRecorData.put("token", "1");
		flowRecorData.put("terminalType", "2");
		flowRecorData.put("operatingType", "1");
		flowRecorData.put("createdBy", "admin");
		flowRecorData.put("creationDate", getCurrentTime());
		flowRecorData.put("lastUpdateBy", "admin");
		flowRecorData.put("lastUpdateDate", getCurrentTime());
		flowRecorData.put("CALL_CNT", 1);
		flowRecorData.put("REMARK", "default");
		flowRecorData.put("STS_CD", "a");

		if (!userService.insertNewLoginRecord(flowRecorData)) {
			code = "400";
			message.setName("invalid user name");
		}

		if (code != "200") {
			return getLoginResponseJSONWithResponse("400", message);
		}
		return getLoginResponseJSONWithResponse("200", message);

	}

	/**
	 * 
	 * @return
	 */
	public String userLogout() {

		PageData pageData = new PageData();
		Subject subject = SecurityUtils.getSubject();
		Session session = SecurityUtils.getSubject().getSession();

		User user = (User) session.getAttribute(Const.SESSION_USER);

		session.removeAttribute(Const.SESSION_USERNAME);
		session.removeAttribute(Const.SESSION_allmenuList);
		session.removeAttribute(Const.ROLE_ID);
		session.removeAttribute(Const.SESSION_USER);
		session.removeAttribute(Const.SESSION_ROLE_RIGHTS);
		session.removeAttribute(Const.SESSION_allmenuList);
		session.removeAttribute(Const.SESSION_menuList);
		session.removeAttribute(Const.SESSION_QX);
		session.removeAttribute(Const.SESSION_userpds);
		session.removeAttribute(Const.SESSION_USERNAME);
		session.removeAttribute(Const.SESSION_USERROL);

		subject.logout();

		PageData flowRecorData = new PageData();

		flowRecorData.put("usiID", user.getUserID());
		flowRecorData.put("token", (UsernamePasswordToken) session.getAttribute(Const.TOKEN));
		flowRecorData.put("terminalType", "2");
		flowRecorData.put("operatingType", "2");
		flowRecorData.put("createdBy", "admin");
		flowRecorData.put("creationDate", getCurrentTime());
		flowRecorData.put("lastUpdateBy", "admin");
		flowRecorData.put("lastUpdateDate", getCurrentTime());
		flowRecorData.put("CALL_CNT", 1);
		flowRecorData.put("REMARK", "default");
		flowRecorData.put("STS_CD", "a");

		try {
			if (!userService.insertNewLoginRecord(pageData)) {
				return getLoginResponseJSON("500", "system is busy");
			}
		} catch (Exception e) {
			return getLoginResponseJSON("500", "system is busy");
		}

		return getLoginResponseJSON("200", "");

	}


	/**
	 * 获取系统当前时间
	 * @return
	 */
	public static String getCurrentTime() {
		Date date = new Date();
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(date).toString();
	}

	/**
	 * 获取请求ip
	 * @param request
	 * @return
	 */
	public static String getClientIP(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 组装登录响应信息
	 * @param code
	 * @param message
	 * @return
	 */
	public static String getLoginResponseJSON(String code, String message) {
		TwoEntityResponse response = new TwoEntityResponse();
		response.setCode(code);
		response.setMsg(message);
		return JSON.toJSONString(response);
	}

	/**
	 * 
	 * @param code
	 * @param message
	 * @return
	 */
	public static String getLoginResponseJSONWithResponse(String code, RegisterResponseMessage message) {

		if (code == "200") {
			message.setUserName("");
			message.setEmail("");
			message.setPassword("");
			message.setPhone("");
			message.setRoleID("");
			message.setSkin("");
			message.setName("");
		} else {
			if (message.getUserName() != "invalid user name") {
				message.setUserName("");
			}
			message.setPassword("");
			message.setName("");
			message.setSkin("");
			if (message.getEmail() != "invalid email address") {
				message.setEmail("");
			}
			if (message.getPhone() != "invalid phone number") {
				message.setPhone("");
			}
			message.setRoleID("");
		}

		RegisterResponse response = new RegisterResponse();
		response.setCode(code);
		response.setMessage(message);

		return JSON.toJSONString(response);

	}

	public static String md5(String data) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(data.getBytes());
		StringBuffer buf = new StringBuffer();
		byte[] bits = md.digest();
		for (int i = 0; i < bits.length; i++) {
			int a = bits[i];
			if (a < 0)
				a += 256;
			if (a < 16)
				buf.append("0");
			buf.append(Integer.toHexString(a));
		}
		return buf.toString();
	}
	
	
	//##############################################################################################
	String menuUrl = "user/listUsers.do"; //菜单地址(权限用)
	

	
	
	
	/**
	 * 保存用户
	 */
	@RequestMapping(value="/saveU")
	public ModelAndView saveU(PrintWriter out) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		
		pd.put("RIGHTS", "");					//权限
		pd.put("LAST_LOGIN", "");				//最后登录时间
		pd.put("IP", "");						//IP
		pd.put("STATUS", "0");					//状态
		pd.put("SKIN", "default");				//默认皮肤
		
		pd.put("PASSWORD",pd.getString("PASSWORD")).toString();
		
		if(null == userService.findByUId(pd)){
			if(Jurisdiction.buttonJurisdiction(menuUrl, "add")){userService.saveU(pd);} //判断新增权限
			mv.addObject("msg","success");
		}else{
			mv.addObject("msg","failed");
		}
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 判断用户名是否存在
	 */
	@RequestMapping(value="/hasU")
	@ResponseBody
	public Object hasU(){
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			if(userService.findByUId(pd) != null){
				errInfo = "error";
			}
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		map.put("result", errInfo);				//返回结果
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 判断邮箱是否存在
	 */
	@RequestMapping(value="/hasE")
	@ResponseBody
	public Object hasE(){
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			
			if(userService.findByUE(pd) != null){
				errInfo = "error";
			}
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		map.put("result", errInfo);				//返回结果
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 判断编码是否存在
	 */
	@RequestMapping(value="/hasN")
	@ResponseBody
	public Object hasN(){
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			if(userService.findByUN(pd) != null){
				errInfo = "error";
			}
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		map.put("result", errInfo);				//返回结果
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 修改用户
	 */
	@RequestMapping(value="/editU")
	public ModelAndView editU() throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		if(pd.getString("PASSWORD") != null && !"".equals(pd.getString("PASSWORD"))){
			pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString());
		}
		if(Jurisdiction.buttonJurisdiction(menuUrl, "edit")){userService.editU(pd);}
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 去修改用户页面
	 */
	@RequestMapping(value="/goEditU")
	public ModelAndView goEditU() throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		
		//顶部修改个人资料
		String fx = pd.getString("fx");
		
		//System.out.println(fx);
		
		if("head".equals(fx)){
			mv.addObject("fx", "head");
		}else{
			mv.addObject("fx", "user");
		}
		
		List<Role> roleList = roleService.listAllERRoles();			//列出所有二级角色
		pd = userService.findByUiId(pd);							//根据ID读取
		mv.setViewName("system/user/user_edit");
		mv.addObject("msg", "editU");
		mv.addObject("pd", pd);
		mv.addObject("roleList", roleList);
		
		return mv;
	}
	
	/**
	 * 去新增用户页面
	 */
	@RequestMapping(value="/goAddU")
	public ModelAndView goAddU()throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		List<Role> roleList;
		
		roleList = roleService.listAllERRoles();			//列出所有二级角色
		
		mv.setViewName("system/user/user_edit");
		mv.addObject("msg", "saveU");
		mv.addObject("pd", pd);
		mv.addObject("roleList", roleList);

		return mv;
	}
	
	/**
	 * 显示用户列表(用户组)
	 */
	@RequestMapping(value="/listUsers")
	public ModelAndView listUsers(Page page)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		
		String USERNAME = pd.getString("USERNAME");
		
		if(null != USERNAME && !"".equals(USERNAME)){
			USERNAME = USERNAME.trim();
			pd.put("USERNAME", USERNAME);
		}
		
		String lastLoginStart = pd.getString("lastLoginStart");
		String lastLoginEnd = pd.getString("lastLoginEnd");
		
		if(lastLoginStart != null && !"".equals(lastLoginStart)){
			lastLoginStart = lastLoginStart+" 00:00:00";
			pd.put("lastLoginStart", lastLoginStart);
		}
		if(lastLoginEnd != null && !"".equals(lastLoginEnd)){
			lastLoginEnd = lastLoginEnd+" 00:00:00";
			pd.put("lastLoginEnd", lastLoginEnd);
		} 
		
		page.setPd(pd);
		List<PageData>	userList = userService.listPdPageUser(page);			//列出用户列表
		
		mv.setViewName("system/user/user_list");
		mv.addObject("userList", userList);
		mv.addObject("pd", pd);
		return mv;
	}

	
	/**
	 * 显示用户列表(tab方式)
	 */
	@RequestMapping(value="/listtabUsers")
	public ModelAndView listtabUsers(Page page)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		List<PageData>	userList = userService.listAllUser(pd);			//列出用户列表
		mv.setViewName("system/user/user_tb_list");
		mv.addObject("userList", userList);
		mv.addObject("pd", pd);
		mv.addObject(Const.SESSION_QX,this.getHC());	//按钮权限
		return mv;
	}
	
	/**
	 * 删除用户
	 */
	@RequestMapping(value="/deleteU")
	public void deleteU(PrintWriter out){
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			if(Jurisdiction.buttonJurisdiction(menuUrl, "del")){userService.deleteU(pd);}
			out.write("success");
			out.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
	}
	
	/**
	 * 批量删除
	 */
	@RequestMapping(value="/deleteAllU")
	@ResponseBody
	public Object deleteAllU() {
		PageData pd = new PageData();
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			pd = this.getPageData();
			List<PageData> pdList = new ArrayList<PageData>();
			String USER_IDS = pd.getString("USER_IDS");
			
			if(null != USER_IDS && !"".equals(USER_IDS)){
				String ArrayUSER_IDS[] = USER_IDS.split(",");
				if(Jurisdiction.buttonJurisdiction(menuUrl, "del")){userService.deleteAllU(ArrayUSER_IDS);}
				pd.put("msg", "ok");
			}else{
				pd.put("msg", "no");
			}
			
			pdList.add(pd);
			map.put("list", pdList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}
	//===================================================================================================
	/*
	 * 导出用户信息到EXCEL
	 * @return
	 */
	@RequestMapping(value="/excel")
	public ModelAndView exportExcel(){
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try{
			if(Jurisdiction.buttonJurisdiction(menuUrl, "cha")){
				//检索条件===
				String USERNAME = pd.getString("USERNAME");
				if(null != USERNAME && !"".equals(USERNAME)){
					USERNAME = USERNAME.trim();
					pd.put("USERNAME", USERNAME);
				}
				String lastLoginStart = pd.getString("lastLoginStart");
				String lastLoginEnd = pd.getString("lastLoginEnd");
				if(lastLoginStart != null && !"".equals(lastLoginStart)){
					lastLoginStart = lastLoginStart+" 00:00:00";
					pd.put("lastLoginStart", lastLoginStart);
				}
				if(lastLoginEnd != null && !"".equals(lastLoginEnd)){
					lastLoginEnd = lastLoginEnd+" 00:00:00";
					pd.put("lastLoginEnd", lastLoginEnd);
				} 
				//检索条件===
				
				Map<String,Object> dataMap = new HashMap<String,Object>();
				List<String> titles = new ArrayList<String>();
				
				titles.add("用户名"); 		//1
				titles.add("编号");  		//2
				titles.add("姓名");			//3
				titles.add("职位");			//4
				titles.add("手机");			//5
				titles.add("邮箱");			//6
				titles.add("最近登录");		//7
				titles.add("上次登录IP");	//8
				
				dataMap.put("titles", titles);
				
				List<PageData> userList = userService.listAllUser(pd);
				List<PageData> varList = new ArrayList<PageData>();
				for(int i=0;i<userList.size();i++){
					PageData vpd = new PageData();
					vpd.put("var1", userList.get(i).getString("USERNAME"));		//1
					vpd.put("var2", userList.get(i).getString("NUMBER"));		//2
					vpd.put("var3", userList.get(i).getString("NAME"));			//3
					vpd.put("var4", userList.get(i).getString("ROLE_NAME"));	//4
					vpd.put("var5", userList.get(i).getString("PHONE"));		//5
					vpd.put("var6", userList.get(i).getString("EMAIL"));		//6
					vpd.put("var7", userList.get(i).getString("LAST_LOGIN"));	//7
					vpd.put("var8", userList.get(i).getString("IP"));			//8
					varList.add(vpd);
				}
				dataMap.put("varList", varList);
				ObjectExcelView erv = new ObjectExcelView();					//执行excel操作
				mv = new ModelAndView(erv,dataMap);
			}
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * 打开上传EXCEL页面
	 */
	@RequestMapping(value="/goUploadExcel")
	public ModelAndView goUploadExcel()throws Exception{
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("system/user/uploadexcel");
		return mv;
	}
	
	/**
	 * 下载模版
	 */
	@RequestMapping(value="/downExcel")
	public void downExcel(HttpServletResponse response)throws Exception{
		
		FileDownload.fileDownload(response, PathUtil.getClasspath() + Const.FILEPATHFILE + "Users.xls", "Users.xls");
		
	}
	
	/**
	 * 从EXCEL导入到数据库
	 */
	@RequestMapping(value="/readExcel")
	public ModelAndView readExcel(
			@RequestParam(value="excel",required=false) MultipartFile file
			) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")){return null;}
		if (null != file && !file.isEmpty()) {
			String filePath = PathUtil.getClasspath() + Const.FILEPATHFILE;								//文件上传路径
			String fileName =  FileUpload.fileUp(file, filePath, "userexcel");							//执行上传
			
			List<PageData> listPd = (List)ObjectExcelRead.readExcel(filePath, fileName, 2, 0, 0);	//执行读EXCEL操作,读出的数据导入List 2:从第3行开始；0:从第A列开始；0:第0个sheet
			
			/*存入数据库操作======================================*/
			pd.put("RIGHTS", "");					//权限
			pd.put("LAST_LOGIN", "");				//最后登录时间
			pd.put("IP", "");						//IP
			pd.put("STATUS", "0");					//状态
			pd.put("SKIN", "default");				//默认皮肤
			
			List<Role> roleList = roleService.listAllERRoles();	//列出所有二级角色
			
			pd.put("ROLE_ID", roleList.get(0).getRoleId());	//设置角色ID为随便第一个
			/**
			 * var0 :编号
			 * var1 :姓名
			 * var2 :手机
			 * var3 :邮箱
			 * var4 :备注
			 */
			for(int i=0;i<listPd.size();i++){		
				pd.put("USER_ID", this.get32UUID());										//ID
				pd.put("NAME", listPd.get(i).getString("var1"));							//姓名
				
				String USERNAME = GetPinyin.getPingYin(listPd.get(i).getString("var1"));	//根据姓名汉字生成全拼
				pd.put("USERNAME", USERNAME);	
				if(userService.findByUId(pd) != null){										//判断用户名是否重复
					USERNAME = GetPinyin.getPingYin(listPd.get(i).getString("var1"))+Tools.getRandomNum();
					pd.put("USERNAME", USERNAME);
				}
				pd.put("BZ", listPd.get(i).getString("var4"));								//备注
				if(Tools.checkEmail(listPd.get(i).getString("var3"))){						//邮箱格式不对就跳过
					pd.put("EMAIL", listPd.get(i).getString("var3"));						
					if(userService.findByUE(pd) != null){									//邮箱已存在就跳过
						continue;
					}
				}else{
					continue;
				}
				
				pd.put("NUMBER", listPd.get(i).getString("var0"));							//编号已存在就跳过
				pd.put("PHONE", listPd.get(i).getString("var2"));							//手机号
				
				pd.put("PASSWORD", new SimpleHash("SHA-1", USERNAME, "123").toString());	//默认密码123
				if(userService.findByUN(pd) != null){
					continue;
				}
				userService.saveU(pd);
			}
			/*存入数据库操作======================================*/
			
			mv.addObject("msg","success");
		}
		
		mv.setViewName("save_result");
		return mv;
	}
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
	}
	

	/* ===============================权限================================== */
	public Map<String, String> getHC(){
		Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
		Session session = currentUser.getSession();
		return (Map<String, String>)session.getAttribute(Const.SESSION_QX);
	}
	/* ===============================权限================================== */
	

}
